<template>
  <div class="calendar-tool">
    <div class="calendar-header">
      <div class="header-left">
        <h2>日历待办</h2>
        <div class="view-switcher">
          <div class="switcher-container">
            <div 
              class="switcher-track"
              :style="{ '--active-position': viewSwitcherPosition }"
            >
              <div class="active-background"></div>
              <button 
                v-for="view in viewOptions" 
                :key="view.value"
                class="switcher-option"
                :class="{ active: currentView === view.value }"
                @click="currentView = view.value"
              >
                <el-icon class="option-icon">
                  <component :is="view.icon" />
                </el-icon>
                <span>{{ view.label }}</span>
              </button>
            </div>
          </div>
        </div>
      </div>
      <div class="header-right">
        <div class="date-navigator">
          <button 
            class="nav-button prev"
            @click="navigateDate('prev')"
          >
            <el-icon><ArrowLeft /></el-icon>
          </button>
          <div class="date-display" @click="showDatePicker = true">
            <div class="current-date">
              {{ formatCurrentDate }}
              <el-icon class="arrow-down"><ArrowDown /></el-icon>
            </div>
            <div class="today-button" @click.stop="goToToday">
              今天
            </div>
          </div>
          <button 
            class="nav-button next"
            @click="navigateDate('next')"
          >
            <el-icon><ArrowRight /></el-icon>
          </button>
        </div>
      </div>
    </div>

    <div class="calendar-body">
      <!-- 月视图 -->
      <div v-if="currentView === 'month'" class="month-view">
        <div class="weekdays">
          <div v-for="day in weekDays" :key="day" class="weekday">{{ day }}</div>
        </div>
        <div class="days">
          <div
            v-for="(day, index) in monthDays"
            :key="index"
            class="day"
            :class="{
              'other-month': day.otherMonth,
              'today': isToday(day.date),
              'selected': isSelected(day.date),
              'holiday': day.lunar.isHoliday
            }"
            @click="selectDate(day.date)"
          >
            <div class="day-content">
              <span class="day-number">{{ day.dayOfMonth }}</span>
              <span class="lunar-day" :class="{ 'festival': day.lunar.festival || day.lunar.term }">
                {{ day.lunar.festival || day.lunar.term || day.lunar.lunarDay }}
              </span>
            </div>
            <div class="todo-indicators" v-if="day.todos.length">
              <span 
                v-for="(todo, todoIndex) in day.todos.slice(0, 3)" 
                :key="todoIndex"
                class="todo-dot"
                :style="{ backgroundColor: todo.color }"
              />
              <span v-if="day.todos.length > 3" class="more-todos">
                +{{ day.todos.length - 3 }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 周视图 - 暂时注释掉 -->
      <!-- <week-view
        v-else-if="currentView === 'week'"
        :selected-date="selectedDate"
      /> -->

      <!-- 日视图 - 暂时注释掉 -->
      <!-- <day-view
        v-else
        :selected-date="selectedDate"
      /> -->
    </div>

    <!-- 添加待办按钮 -->
    <div class="add-todo-button" @click="showAddTodoDialog = true">
      <div class="button-content">
        <el-icon><Plus /></el-icon>
        <span>新建待办</span>
      </div>
    </div>

    <!-- 添加待办对话框 -->
    <el-dialog
      v-model="showAddTodoDialog"
      :show-close="false"
      width="480px"
      class="add-todo-dialog"
      top="15vh"
    >
      <div class="dialog-header">
        <h3>新建待办</h3>
        <el-button 
          class="close-button" 
          circle
          @click="showAddTodoDialog = false"
        >
          <el-icon><Close /></el-icon>
        </el-button>
      </div>

      <el-form
        ref="todoFormRef"
        :model="todoForm"
        :rules="todoRules"
        class="todo-form"
      >
        <el-form-item prop="title">
          <el-input
            v-model="todoForm.title"
            placeholder="待办事项"
            :prefix-icon="Edit"
            clearable
          />
        </el-form-item>

        <div class="form-row">
          <el-form-item prop="date" class="date-item">
            <el-date-picker
              v-model="todoForm.date"
              type="date"
              placeholder="选择日期"
              :prefix-icon="Calendar"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item prop="time" class="time-item">
            <el-time-picker
              v-model="todoForm.time"
              format="HH:mm"
              placeholder="选择时间"
              :prefix-icon="Clock"
              style="width: 100%"
            />
          </el-form-item>
        </div>

        <el-form-item prop="description">
          <el-input
            v-model="todoForm.description"
            type="textarea"
            rows="3"
            placeholder="添加描述..."
            resize="none"
          />
        </el-form-item>

        <div class="form-row">
          <el-form-item label="标签颜色" class="color-item">
            <el-color-picker 
              v-model="todoForm.color"
              :predefine="predefineColors"
            />
          </el-form-item>

          <el-form-item label="提醒" class="reminder-item">
            <el-switch
              v-model="todoForm.reminder"
              active-text="开启提醒"
            />
          </el-form-item>
        </div>
      </el-form>

      <div class="dialog-footer">
        <el-button @click="showAddTodoDialog = false">取消</el-button>
        <el-button type="primary" @click="handleAddTodo">创建</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { 
  ArrowLeft, 
  ArrowRight, 
  ArrowDown,
  ArrowUp,
  Plus, 
  Calendar, 
  Timer, 
  Clock,
  Edit,
  Close
} from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import dayjs from 'dayjs'
import { useTodos } from './composables/useTodos'
import { getLunarInfo } from './utils/lunarCalendar'

const {
  showAddTodoDialog,
  todoFormRef,
  todoForm,
  todoRules,
  handleAddTodo,
  resetForm
} = useTodos()

// 监听对话框关闭
watch(() => showAddTodoDialog.value, (show) => {
  if (!show) {
    resetForm()
  }
})

// 视图选项配置
const viewOptions = [
  { value: 'month', label: '月', icon: Calendar },
  { value: 'week', label: '周', icon: Timer },
  { value: 'day', label: '日', icon: Clock }
]

const currentView = ref('month')

// 计算滑块位置
const viewSwitcherPosition = computed(() => {
  const index = viewOptions.findIndex(option => option.value === currentView.value)
  return `${index * 100}%`
})

// 当前选中日期
const selectedDate = ref(dayjs())

// 星期几
const weekDays = ['日', '一', '二', '三', '四', '五', '六']

// 格式化当前日期显示
const formatCurrentDate = computed(() => {
  const date = selectedDate.value
  if (currentView.value === 'month') {
    return date.format('YYYY年 M月')
  } else if (currentView.value === 'week') {
    return `${date.format('YYYY年 M月 D日')} - ${date.add(6, 'day').format('M月 D日')}`
  } else {
    return date.format('YYYY年 M月 D日')
  }
})

// 获取月视图数据
const monthDays = computed(() => {
  const date = selectedDate.value
  const firstDay = date.startOf('month')
  const lastDay = date.endOf('month')
  const days = []

  // 获取上个月的天数
  const prevMonthDays = firstDay.day()
  for (let i = prevMonthDays - 1; i >= 0; i--) {
    const currentDate = firstDay.subtract(i + 1, 'day')
    days.push({
      date: currentDate,
      dayOfMonth: currentDate.date(),
      otherMonth: true,
      todos: [], // TODO: 获取待办事项
      lunar: getLunarInfo(currentDate.toDate())
    })
  }

  // 获取当前月的天数
  for (let i = 0; i < lastDay.date(); i++) {
    const currentDate = firstDay.add(i, 'day')
    days.push({
      date: currentDate,
      dayOfMonth: i + 1,
      otherMonth: false,
      todos: [], // TODO: 获取待办事项
      lunar: getLunarInfo(currentDate.toDate())
    })
  }

  // 获取下个月的天数
  const nextMonthDays = 42 - days.length
  for (let i = 0; i < nextMonthDays; i++) {
    const currentDate = lastDay.add(i + 1, 'day')
    days.push({
      date: currentDate,
      dayOfMonth: i + 1,
      otherMonth: true,
      todos: [], // TODO: 获取待办事项
      lunar: getLunarInfo(currentDate.toDate())
    })
  }

  return days
})

// 日期导航
const navigateDate = (direction: 'prev' | 'next') => {
  if (currentView.value === 'month') {
    selectedDate.value = direction === 'prev' 
      ? selectedDate.value.subtract(1, 'month')
      : selectedDate.value.add(1, 'month')
  } else if (currentView.value === 'week') {
    selectedDate.value = direction === 'prev'
      ? selectedDate.value.subtract(1, 'week')
      : selectedDate.value.add(1, 'week')
  } else {
    selectedDate.value = direction === 'prev'
      ? selectedDate.value.subtract(1, 'day')
      : selectedDate.value.add(1, 'day')
  }
}

// 检查是否是今天
const isToday = (date: dayjs.Dayjs) => {
  return date.format('YYYY-MM-DD') === dayjs().format('YYYY-MM-DD')
}

// 检查是否是选中日期
const isSelected = (date: dayjs.Dayjs) => {
  return date.format('YYYY-MM-DD') === selectedDate.value.format('YYYY-MM-DD')
}

// 选择日期
const selectDate = (date: dayjs.Dayjs) => {
  selectedDate.value = date
}

// 跳转到今天
const goToToday = () => {
  selectedDate.value = dayjs()
}

// 预定义颜色
const predefineColors = [
  '#409EFF',
  '#67C23A',
  '#E6A23C',
  '#F56C6C',
  '#909399',
  '#6B7280',
  '#8B5CF6',
  '#EC4899'
]
</script>

<style lang="scss" scoped>
.calendar-tool {
  padding: 24px;
  max-width: 1200px;
  margin: 0 auto;
  background: var(--el-bg-color);
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);

  .calendar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 32px;
    padding: 0 8px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 32px;

      h2 {
        margin: 0;
        font-size: 28px;
        font-weight: 600;
        background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-light-3));
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        letter-spacing: -0.5px;
      }

      .view-switcher {
        .switcher-container {
          background: var(--el-fill-color-light);
          padding: 4px;
          border-radius: 12px;
          position: relative;
          width: 240px;

          .switcher-track {
            position: relative;
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            gap: 4px;
            height: 36px;

            .active-background {
              position: absolute;
              width: calc(33.33% - 4px);
              height: calc(100% - 4px);
              background: var(--el-bg-color);
              border-radius: 8px;
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
              left: 2px;
              top: 2px;
              transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
              transform: translateX(var(--active-position));
              z-index: 1;
            }

            .switcher-option {
              position: relative;
              z-index: 2;
              border: none;
              background: none;
              cursor: pointer;
              padding: 0 12px;
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 6px;
              color: var(--el-text-color-secondary);
              font-size: 14px;
              font-weight: 500;
              transition: all 0.3s ease;

              &:hover {
                color: var(--el-text-color-primary);
              }

              &.active {
                color: var(--el-color-primary);

                .option-icon {
                  transform: scale(1.1);
                }
              }

              .option-icon {
                font-size: 16px;
                transition: transform 0.3s ease;
              }
            }
          }
        }
      }
    }

    .header-right {
      display: flex;
      align-items: center;
      gap: 24px;

      .date-navigator {
        display: flex;
        align-items: center;
        gap: 16px;
        background: var(--el-fill-color-light);
        padding: 8px 16px;
        border-radius: 12px;

        .date-display {
          display: flex;
          align-items: center;
          gap: 12px;
          padding: 0 16px;
          height: 36px;
          cursor: pointer;
          position: relative;
          min-width: 200px;

          .current-date {
            font-size: 15px;
            font-weight: 600;
            color: var(--el-text-color-primary);
            letter-spacing: -0.3px;
            display: flex;
            align-items: center;
            gap: 6px;

            .arrow-down {
              font-size: 14px;
              color: var(--el-text-color-secondary);
              transition: transform 0.3s ease;
            }

            &:hover .arrow-down {
              transform: translateY(2px);
            }
          }
        }

        .today-button {
          padding: 2px 8px;
          border-radius: 4px;
          font-size: 13px;
          color: var(--el-color-primary);
          background: var(--el-color-primary-light-9);
          transition: all 0.3s ease;

          &:hover {
            background: var(--el-color-primary-light-8);
            transform: translateY(-1px);
          }

          &:active {
            transform: translateY(0);
          }
        }

        .el-button {
          --el-button-hover-bg-color: var(--el-color-primary-light-8);
          --el-button-hover-text-color: var(--el-color-primary);
        }
      }
    }
  }

  .calendar-body {
    background: var(--el-bg-color-overlay);
    border-radius: 16px;
    overflow: hidden;
    border: 1px solid var(--el-border-color-lighter);

    .month-view {
      .weekdays {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        background: var(--el-fill-color-light);
        border-bottom: 1px solid var(--el-border-color-lighter);

        .weekday {
          padding: 16px;
          text-align: center;
          font-weight: 500;
          color: var(--el-text-color-regular);
          font-size: 14px;
        }
      }

      .days {
        display: grid;
        grid-template-columns: repeat(7, 1fr);

        .day {
          aspect-ratio: 1;
          padding: 12px;
          border-right: 1px solid var(--el-border-color-lighter);
          border-bottom: 1px solid var(--el-border-color-lighter);
          cursor: pointer;
          transition: all 0.3s ease;
          position: relative;
          display: flex;
          flex-direction: column;

          &:hover {
            background: var(--el-fill-color-light);
          }

          &.other-month {
            color: var(--el-text-color-placeholder);
            background: var(--el-fill-color-lighter);
          }

          &.today {
            .day-number {
              background: var(--el-color-primary);
              color: white;
              font-weight: 600;
            }
          }

          &.selected {
            background: var(--el-color-primary-light-9);
            
            &::after {
              content: '';
              position: absolute;
              inset: 0;
              border: 2px solid var(--el-color-primary);
              border-radius: 4px;
              pointer-events: none;
            }
          }

          .day-content {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 2px;
          }

          .day-number {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 32px;
            height: 32px;
            border-radius: 50%;
            font-size: 14px;
            margin-bottom: 4px;
          }

          .lunar-day {
            font-size: 12px;
            color: var(--el-text-color-secondary);
            line-height: 1.2;
            
            &.festival {
              color: var(--el-color-danger);
              font-weight: 500;
            }
          }

          &.holiday {
            .day-number {
              color: var(--el-color-danger);
            }
          }

          .todo-indicators {
            margin-top: auto;
            display: flex;
            gap: 4px;
            align-items: center;
            padding: 4px;
            background: rgba(255, 255, 255, 0.8);
            border-radius: 12px;
            backdrop-filter: blur(4px);

            .todo-dot {
              width: 8px;
              height: 8px;
              border-radius: 50%;
              box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }

            .more-todos {
              font-size: 12px;
              color: var(--el-text-color-secondary);
              margin-left: 2px;
            }
          }
        }
      }
    }
  }

  .add-todo-button {
    position: fixed;
    right: 40px;
    bottom: 40px;
    z-index: 100;

    .button-content {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 12px 24px;
      background: var(--el-color-primary);
      border-radius: 16px;
      color: white;
      font-weight: 500;
      cursor: pointer;
      transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
      box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.3);

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 16px rgba(var(--el-color-primary-rgb), 0.4);
      }

      &:active {
        transform: translateY(0);
      }

      .el-icon {
        font-size: 18px;
      }
    }
  }

  .add-todo-dialog {
    :deep(.el-dialog) {
      border-radius: 20px;
      overflow: hidden;
      box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
      
      .el-dialog__header {
        display: none;
      }

      .el-dialog__body {
        padding: 0;
      }
    }

    .dialog-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 20px 24px;
      border-bottom: 1px solid var(--el-border-color-lighter);

      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 600;
      }

      .close-button {
        --el-button-hover-bg-color: var(--el-fill-color-light);
        --el-button-hover-text-color: var(--el-text-color-regular);
      }
    }

    .todo-form {
      padding: 24px;

      .form-row {
        display: flex;
        gap: 16px;

        .date-item,
        .time-item {
          flex: 1;
        }

        .color-item {
          margin-right: auto;
        }
      }

      :deep(.el-form-item) {
        margin-bottom: 20px;

        &:last-child {
          margin-bottom: 0;
        }
      }

      :deep(.el-input__wrapper),
      :deep(.el-textarea__inner) {
        box-shadow: none;
        border: 1px solid var(--el-border-color);
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover,
        &:focus {
          border-color: var(--el-color-primary);
          box-shadow: 0 0 0 1px var(--el-color-primary-light-8);
        }
      }
    }

    .dialog-footer {
      padding: 16px 24px;
      border-top: 1px solid var(--el-border-color-lighter);
      display: flex;
      justify-content: flex-end;
      gap: 12px;
    }
  }

  // 暗黑模式适配
  :root.dark {
    .calendar-tool {
      background: var(--el-bg-color-overlay);
      box-shadow: 0 4px 24px rgba(0, 0, 0, 0.2);

      .calendar-body {
        background: rgba(255, 255, 255, 0.02);
        border-color: rgba(255, 255, 255, 0.1);

        .month-view {
          .days {
            .day {
              .todo-indicators {
                background: rgba(0, 0, 0, 0.3);
              }
            }
          }
        }
      }
    }

    .add-todo-button {
      .button-content {
        box-shadow: 0 4px 12px rgba(var(--el-color-primary-rgb), 0.4);

        &:hover {
          box-shadow: 0 8px 16px rgba(var(--el-color-primary-rgb), 0.5);
        }
      }
    }

    .add-todo-dialog {
      :deep(.el-dialog) {
        background: var(--el-bg-color);
        box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
      }
    }
  }

  // 响应式适配
  @media (max-width: 768px) {
    .calendar-tool {
      padding: 16px;
      border-radius: 0;

      .calendar-header {
        flex-direction: column;
        gap: 20px;
        margin-bottom: 24px;

        .header-left {
          width: 100%;
          justify-content: space-between;
          gap: 16px;

          h2 {
            font-size: 24px;
          }
        }

        .header-right {
          width: 100%;
          justify-content: space-between;
        }
      }
    }

    .add-todo-button {
      right: 20px;
      bottom: 20px;

      .button-content {
        padding: 10px 20px;
      }
    }

    .add-todo-dialog {
      :deep(.el-dialog) {
        width: 90% !important;
        margin: 0 auto;
      }
    }
  }
}
</style>